package com.hyz.reggie.aop;

import com.hyz.reggie.dao.LogDao;
import com.hyz.reggie.pojo.AcquireExecption;
import com.hyz.reggie.pojo.Log;
import com.hyz.reggie.pojo.R;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
@Aspect
@Slf4j
public class LogAop {
    private Date startTime;
    private Date endTime;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private LogDao dao;


    @Around("execution(* com.hyz.reggie.controller.*Controller.*(..))")
    public Object log(ProceedingJoinPoint pjp) throws Throwable {
        startTime = new Date();
        Log log = new Log();
        R proceed = null;
        try {
            proceed = (R) pjp.proceed();
        } catch (AcquireExecption ac) {
            log.setLoginMsg(ac.getMessage());
            throw new AcquireExecption(ac.getMessage());
        }
        Signature signature = pjp.getSignature();
        String name = signature.getName();
        String addr = request.getRemoteAddr();
        endTime = new Date();
        log.setIp(addr);
        log.setCreatedTime(startTime);
        log.setEndTime(endTime);
        log.setUseInterface(name);
        log.setUseTime(endTime.getTime() - startTime.getTime());
        log.setLoginMsg(proceed.getCode()==1?"操作成功":"操作失败");
        dao.insert(log);
        return proceed;
    }

}
